from socket import socket,AF_INET,SOCK_STREAM,SOL_SOCKET,SO_REUSEADDR
import threading
from time import sleep

#  创建socket
soc = socket(AF_INET, SOCK_STREAM)
# 设置端口可复用，保证我们每次按Ctrl+C组合键之后，快速重启
#soc.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
#  监听端口
soc.bind(('', 6666))#192.168.199.213

# listen()方法开始监听端口，传入的参数指定等待连接的最大数量
soc.listen(5)
print('waiting for connection...')


def Tcplink(sock, addr):
    print('Accept new connection form %s:%s...' % addr)
    #sock.send(b'Welcome!')
    while True:
        data = sock.recv(1024)
        sleep(1)
        # if not data:#or data.decode('utf-8') == 'exit'
        #     break
        sock.send(('Have Received: %s!' % data.decode('utf-8')).encode('utf-8'))
        #  sock.close()
        print('Connection from %s Received: %s  ' % addr, data)
        if data!='':
            return data

def send_command(sock,command):
    sock.send(command.encode('utf-8'))#.decode('utf-8')
    sock.close()

if __name__ =="__main__":
    sock, addr = soc.accept()
    send_command(sock, 'pause')
    #  创建新线程来处理连接
    #Tcplink(sock, addr)

    # t = threading.Thread(target=send_command, args='stop')
    # t.start()

    #data = sock.recv(1024)

    # while True:
    #     #  接受一个新连接：
    #     sock, addr = soc.accept()
    #     #  创建新线程来处理连接
    #
    #     t = threading.Thread(target=Tcplink(sock, addr), args=(sock, addr))
    #     t.start()
    #     data = sock.recv(1024)
    #     sleep(1)
    #     if  data.decode('utf-8') == 'exit':#not data or
    #         break